import { PopState, FooterShow, Mutations, SaveName, StrLenth, SelectorTag, RouteUrl, Url_Key, JWT_EXPIRED_ERROR_CODE } from 'src/common/const';
import Validation from "src/common/util/validation";
import { RequestUrl } from 'src/common/url';
import validation from './util/validation';

// 验证码倒计时
sessionStorage["overTime"] = parseInt(60);
// let overTime = parseInt(60);
let timeOut = null;
export default {
  canvasDataURL(path, obj, _this, name) {
    var img = new Image();
    img.src = path;
    img.onload = function () {
      var that = this;
      // 默认按比例压缩
      var w = that.width,
        h = that.height,
        scale = w / h;
      w = obj.width || w;
      h = obj.height || (w / scale);
      var quality = 0.7;  // 默认图片质量为0.7
      //生成canvas
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');
      // 创建属性节点
      var anw = document.createAttribute("width");
      anw.nodeValue = w;
      var anh = document.createAttribute("height");
      anh.nodeValue = h;
      canvas.setAttributeNode(anw);
      canvas.setAttributeNode(anh);
      ctx.drawImage(that, 0, 0, w, h);
      // 图像质量
      if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
        quality = obj.quality;
      }
      // debugger
      // quality值越小，所绘制出的图像越模糊
      var dataurl = canvas.toDataURL('image/jpeg', quality);
      // console.log(dataurl);
      // console.log('22222222222222222222222');
      // 回调函数返回base64的值
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      let senFile = new File([u8arr], name, { type: mime });

      // let reader = new FileReader();
      // reader.readAsDataURL(senFile);
      // reader.onload = function (event) {
      //   console.log(event.target.result);
      // };
      _this.initData.uploadAllImages.push(senFile);
    }
  },
  getDateCurrency(val) {
    val += "";
    return val.replace("-", "/").replace("-", "/").replace("-", "/");
  },
  getNewObject(val) {
    let resObj = JSON.stringify(val);
    return JSON.parse(resObj);
  },
  //重新获取用户信息，根据jwt的token（适用于jwt失效的情况）
  reJwtVal(data) {
    if (typeof (data.state) != "undefined" && data.state == JWT_EXPIRED_ERROR_CODE) {

      this.jwtQuery();//请求并获取jwt的token

      //获取本地用户JSON信息
      let userInfo = JSON.parse(localStorage[SaveName.LOCAL_STORAGE_USER]);
      if (typeof (userInfo) != "undefined" && typeof (userInfo.id) != "undefined") {
        let query = { id: userInfo.id };
        //传参当前获取过jwt的token到接口
        let localToken = localStorage[SaveName.JWT_TOKEN_NAME];
        let _this = this;
        $.ajax({
          type: "POST",
          url: RequestUrl.FIND_USER_BY_ID,
          data: query,
          async: false,
          headers: {
            "authorization": localToken,
          },
          success: function (res, status, xhr) {
            let jwtToken = xhr.getResponseHeader(SaveName.JWT_TOKEN_NAME);
            //保存token到本地便于下次接口带参校验
            if (_this.isNotEmpty(jwtToken) && jwtToken != localToken) {
              //token变化时才覆盖
              localStorage[SaveName.JWT_TOKEN_NAME] = jwtToken;
            }
          }
        });
      }
      //失效的jwt页面强制刷新
      location.reload();
    }
  },
  getJwtVal() {
    //判断本地是否已有token
    let localToken = localStorage[SaveName.JWT_TOKEN_NAME];
    let url = window.location.href;
    let _this = this;
    if (this.isEmpty(localToken) || url.indexOf("lcb") > -1 || url.indexOf("LCB") > -1) {
      this.jwtQuery();
    } else {//已保存过token
      $.ajax({
        type: "POST",
        url: RequestUrl.VAL_DATA,
        async: false,
        headers: {
          "authorization": localToken,
          // "Accept": "application/json; charset=utf-8",
          // "Content-Type": "application/x-www-form-urlencoded",
        },
        success: function (res, status, xhr) {
          _this.reJwtVal(res);


          let jwtToken = xhr.getResponseHeader(SaveName.JWT_TOKEN_NAME);
          // console.log("已存在的：" + jwtToken);
          //保存token
          if (_this.isNotEmpty(jwtToken) && jwtToken != localToken) {
            //token变化时才覆盖
            localStorage[SaveName.JWT_TOKEN_NAME] = jwtToken;
          }


          // localStorage[SaveName.JWT_TOKEN_NAME] = jwtToken;
          sessionStorage["IS_JWT_QUERY"] = "T";
        }
      });
    }
  },
  showErrorMsg(_this, errorMsg) {
    _this.$vux.alert.show({ content: _this.$common.alertMsg(errorMsg, "red;") });
    // setTimeout(() => {
    //   this.$vux.alert.hide();
    // }, 3000);
    return false;
  },
  //请求并获取jwt的token
  jwtQuery() {
    let _this = this;
    let localToken = localStorage[SaveName.JWT_TOKEN_NAME];
    $.ajax({
      type: "POST",
      url: RequestUrl.VAL_DATA,
      async: false,
      success: function (res, status, xhr) {
        let jwtToken = xhr.getResponseHeader(SaveName.JWT_TOKEN_NAME);
        // console.log("第一次获取：" + jwtToken);
        //保存token
        if (_this.isNotEmpty(jwtToken) && jwtToken != localToken) {
          //token变化时才覆盖
          localStorage[SaveName.JWT_TOKEN_NAME] = jwtToken;
        }
        sessionStorage["IS_JWT_QUERY"] = "T";
      }
    });
  },
  /** 判断是否为空 */
  isEmpty(data) {
    return validation.isEmpty(data);
  },
  mask(str, begin, end, char) {
    // debugger
    let fstStr = str.substring(0, begin);
    let scdStr = str.substring(begin, end);
    let lstStr = str.substring(end, str.length);
    // let matchExp = /w/g;
    // let resSt = fstStr + scdStr.replace('/w/g', char) + lstStr;
    let charres = "";
    for (let i = 0; i < scdStr.length; i++) {
      charres += char
    }
    let resSt = fstStr + charres + lstStr;
    return resSt;
  },
  /** 判断是否不为空 */
  isNotEmpty(data) {
    return validation.isNotEmpty(data);
  },
  /** 中英文判断 */
  getIsCh(_this) {
    return true;
  },
  /**
   * 下载文件到本地
   * @param {*} url 
   */
  downloadfile(url, name, _this) {

    // var iframe = document.createElement("iframe");
    // iframe.src = url;
    // iframe.style.display = "none";
    // document.body.appendChild(iframe);
    if (localStorage["BOTYPE"] == "A" || localStorage["BOTYPE"] == "O") {

      var iframe = document.createElement("iframe");
      iframe.src = url;
      iframe.style.display = "none";
      document.body.appendChild(iframe);
    } else {
      window.location.href = url;
    }
    // window.location.href = url;



    // var aLink = document.createElement('a');
    // var blob = new Blob([url]);
    // var evt = document.createEvent("HTMLEvents");
    // evt.initEvent("click", false, false);//initEvent 不加后两个参数在FF下会报错, 感谢 Barret Lee 的反馈
    // // aLink.download = fileName;
    // aLink.href = URL.createObjectURL(blob);
    // aLink.dispatchEvent(evt);
  },
  /**
   * 设置返回的方式
   * @param {*} _this 
   */
  goBack(_this) {
    // let iframe = {
    //   isIframe: false
    // };
    // _this.$store.commit(Mutations.SET_IFRAME_DATA, iframe);
    _this.$store.commit(Mutations.POP_STATE, PopState.VUX_POP_OUT);
    window.history.go(-1);
  },
  /**
   * 跳转路由
   * @param {*} _this 
   * @param {*} url 
   */
  goUrl(_this, url, parm) {
    _this.$store.commit(Mutations.POP_STATE, PopState.VUX_POP_IN);
    if (!this.isEmpty(parm)) {
      //有参路由
      _this.$router.push({
        path: url + parm
      });
    } else {
      //无参路由
      _this.$router.push({
        path: url
      });
    }
  },
  /**
   * 跳转路由
   * @param {*} _this 
   * @param {*} url 
   */
  goBackUrl(_this, url, parm) {
    _this.$store.commit(Mutations.POP_STATE, PopState.VUX_POP_OUT);
    if (!this.isEmpty(parm)) {
      //有参路由
      _this.$router.push({
        path: url + parm
      });
    } else {
      //无参路由
      _this.$router.push({
        path: url
      });
    }
  },
  getShareIndexUrl(_this, data) {
    let uuidShare = data.shareId;
    if (uuidShare.indexOf("isappinstalled") >= 0) {
      let uuid = _this.$common.getUuid();
      _this.$common.storeCommit(_this, Mutations.SET_SHARE_UUID, uuid);
      uuidShare = uuid;
    }
    let urlParm = "";
    // if (!this.isEmpty(data.shareId)) {
    urlParm += "?&==";
    urlParm += uuidShare += "/P=";
    // }

    return urlParm;

  },
  setShareUrl(list) {
    let urlParm = "?&";
    for (let i = 0; i < list.length; i++) {
      if (i > 0) {
        urlParm += "&";
      }
      urlParm += list[i].key + "=" + list[i].value;
    }
    return urlParm;
  },
  getShareUrl(_this, data) {
    // let urlParm = "?&=";
    // if (!this.isEmpty(data.id)) {
    //   urlParm += data.id + '/';
    // }
    // if (data.isLogin) {
    //   urlParm += data.userDto.userCode + "/U=";
    // } else {
    //   urlParm += "/P=";
    // }
    let uuidShare = data.shareId;
    if (uuidShare.indexOf("isappinstalled") >= 0) {
      let uuid = _this.$common.getUuid();
      _this.$common.storeCommit(_this, Mutations.SET_SHARE_UUID, uuid);
      uuidShare = uuid;
    }
    let urlParm = "?&==";
    if (!this.isEmpty(data.id)) {
      urlParm += data.id + '/';
      urlParm += data.shareId += "/P=";
    }

    return urlParm;

  },
  saveShare(type, _this, id) {
    // console.log(type);
    let userCode = "";
    let saleAgr = {
      agrementNo: "",
      saleCode: "",
      saleName: "",
      channelName: "",
    };
    let isSetAge = true;
    let isHotArea = false;
    let areaCode = "";
    let shareUuid = _this.shareUuid;
    if (sessionStorage["SHARE_COMMON_TYPE"] == "REF" && _this.$common.isNotEmpty(_this.saveInsure.refShareUUid)) {
      shareUuid = _this.saveInsure.refShareUUid;
    }
    if (_this.user.isLogin) {
      userCode = _this.user.userDto.userCode;
      if (_this.$common.isNotEmpty(_this.user.userDto.agrementNo)) {
        isSetAge = false;
        saleAgr.agrementNo = _this.user.userDto.agrementNo;
        saleAgr.saleCode = _this.user.userDto.saleCode;
        saleAgr.saleName = _this.user.userDto.saleName;
        saleAgr.channelName = _this.user.userDto.channelName;
      } else if (!_this.$common.isEmpty(_this.user.userDto.areaCode) && isSetAge) {
        areaCode = _this.user.userDto.areaCode;
        isSetAge = false;
        isHotArea = true;
      }
    }
    if (isSetAge) {
      saleAgr.agrementNo = _this.saveInsure.hotArea.agreementNo;
      saleAgr.saleCode = _this.saveInsure.hotArea.saleCode;
      saleAgr.saleName = _this.saveInsure.hotArea.saleName;
      saleAgr.channelName = _this.saveInsure.hotArea.branchName;
    }
    if (saleAgr.saleCode == "null" || saleAgr.saleCode == "undefined" || saleAgr.saleCode == null) {
      saleAgr.saleCode = "";
      saleAgr.saleName = "";
    }
    if (saleAgr.channelName == "null" || saleAgr.channelName == "undefined" || saleAgr.channelName == null) {
      saleAgr.channelName = "";
    }
    let isTrigger = false;
    let proId = ""
    if (id == 1) {
      proId = "首页";
    } else if (id == 2) {
      proId = "更多";
    } else if (id == 3) {
      isTrigger = true;
      proId = "商店";
    } else if (id == 4) {
      isTrigger = true;
      // proId = "软文" + _this.id;
      proId = "软文";
    } else if (id == 5) {
      isTrigger = true;
      // proId = "产品" + _this.saveInsure.indexData.id;
      proId = "产品";
    } else if (id == 6) {
      isTrigger = true;
      // proId = "海报:" + _this.id;
      proId = "海报";
    } else if (id == 7) {
      isTrigger = true;
      proId = "新春大聚惠";
    } else if (id == 8) {
      isTrigger = true;
      proId = "渠道";
    }

    if (this.isEmpty(saleAgr.agrementNo)) {
      saleAgr.agrementNo = "";
    }
    shareUuid = shareUuid.trim();
    let shareData = {
      TYPE: "FORM",
      userCode: userCode,
      shareId: shareUuid,
      productId: proId,
      shareType: type,
      agrementNo: saleAgr.agrementNo,
      saleCode: saleAgr.saleCode,
      saleName: saleAgr.saleName,
      channelName: saleAgr.channelName,
      isHotArea: isHotArea,
      areaCode: areaCode,
      refUuid: _this.saveInsure.refShareUUid,
    };
    let uuidShare = _this.shareUuid + "";
    _this.$http.post(RequestUrl.SAVE_SHARE, shareData).then(function (res) {
      if (type == "微信-朋友圈" && isTrigger) {
        _this.$common.storeCommit(_this, Mutations.SET_TRIGGER, true);
      }
    });
  },
  /**
   * 提交状态methodName=方法名,parametersDto=数据对象
   * @param {*} _this 
   * @param {*} methodName 
   * @param {*} data 
   */
  storeCommit(_this, methodName, data) {
    if (this.isEmpty(data)) {
      _this.$store.commit(methodName);
    } else {
      _this.$store.commit(methodName, data);
    }
  },
  /**
   * 跳转我的客服
   * @param {*} _this 
   */
  goCustomerService(_this) {
    let iframe = {
      isIframe: true,
      iframeUrl: _this.initUrl['CUSTOMER_SERVICE'],
      iframeName: "我的客服",
    };
    _this.$store.commit(Mutations.FOOTER_SHOW, FooterShow.FALSE);
    _this.$store.commit(Mutations.SET_IFRAME_DATA, iframe);

  },
  /**
   * 获取当前ip地址对应的地区信息
   * @param {*} _this 
   */
  getRegion(_this) {
    _this.$http.post(RequestUrl.GET_ADDRESS, {
      TYPE: "FORM",
      url: RequestUrl.IP_REGION,
      charset: "GBK"
    })
      .then(function (res) {
        // 以返回的数据的空格割
        if (typeof (res.result) != 'undefined') {
          let array = res.result.split("	");
          _this.$store.commit(Mutations.INSURE_SET_REGION, array);
          // let country = array[3]; // 国际
          // let province = array[4]; // 省份
          // let city = array[5]; // 市区
          // _this.ipRegionInfo.province = province;
          _this.init();
        }
      })
  },
  /**
   * 发送短信验证码
   * @param {*} _this 
   * @param {*} mobile 
   * @param {*} imgCode 
   * @param {*} isSendOk 
   */
  sendSMS(_this, mobile, imgCode, isSendOk, typeName) {
    _this.isSendOk = true; //禁用按钮和手机号输入
    let _jsThis = this;
    //_this表示操作页面对象
    let msg = Validation.isPhone11(mobile);
    if (msg != null) {
      _this.errorMessage = msg;
      _this.haveError = true; //显示错误信息
      _this.isSendOk = false; //解禁按钮和手机号输入

      _this.showToastText = msg; _this.showToast = true;
      return;
    }
    // 请求参数
    let initData = {
      TYPE: "FORM",
      mobile: mobile,
      typeName: typeName,
    };
    //默认请求获取无图形码
    let postUrl = RequestUrl.SMS_CODE;
    if (!_jsThis.isEmpty(imgCode)) {
      //获取短信验证码 & 图形码
      postUrl = RequestUrl.SMS_CODE_AND_IMG_CODE;
      initData.imgCode = imgCode;
    }
    _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, true);
    _this.$http.post(postUrl, initData).then(function (res) {
      _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, false);
      //请求结果
      if (res.state == 0) {
        _this.errorMessage = "";
        _this.haveError = false;
        //倒计时
        _jsThis.smsTime(_this, _jsThis);
      } else {
        _this.isSendOk = false; //解禁按钮和手机号输入
        _this.errorMessage = res.result;
        _this.haveError = true; //显示错误信息

        _this.showToastText = res.result; _this.showToast = true;
      }
    })
  },
  /**
   * 短信验证码倒计时
   * @param {*} _this 
   * @param {*} _jsThis 
   */
  smsTime(_this, _jsThis) {
    if (sessionStorage["overTime"] == 0) {
      _this.sendBtnText = "获取验证码";
      _this.isSendOk = false; //解禁按钮和手机号输入
      sessionStorage["overTime"] = parseInt(60);
      _jsThis.clearTimeOutForSms();
    } else {
      if (!_this.isSendOk) {
        _this.isSendOk = true; //禁用按钮和手机号输入
      }
      _this.sendBtnText = parseInt(sessionStorage["overTime"]) + "s后再试";
      sessionStorage["overTime"]--;
      _jsThis.timeOut = setTimeout(function () {
        _jsThis.smsTime(_this, _jsThis);
      }, 1000);
    }
  },
  //清除验证码倒计时
  clearTimeOutForSms() {
    if (typeof (this.timeOut) != 'undefined' && this.timeOut != 'undefined' && this.timeOut != null) {
      clearTimeout(this.timeOut);
    }
    sessionStorage["overTime"] = parseInt(60);
  },
  //过滤selector组件无效选项的key值
  filterSelect(val, arrayList) {
    if (val != SelectorTag.keyNull) {
      for (let i = 0; i < arrayList.length; i++) {
        if (arrayList[i].key === SelectorTag.keyNull) {
          //删除请选择项
          arrayList.splice(i, 1);
          break;
        }
      }
    }
    return arrayList;
  },
  /**
   * 获取UUID
   */
  getUuid() {
    let hexDigits = "0123456789abcdef";
    let s = [];
    for (let i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the
    // clock_seq_hi_and_reserved
    // to 01
    // s[8] = s[13] = s[18] = s[23] = "-";

    let uuid = s.join("");

    return uuid;
  },
  //----------------------------------------------------localStorage--openId
  /**
   * 保存微信openid到localStorage中
   * @param {*} openid
   */
  saveOpenIdByLocal(openid) {
    localStorage[SaveName.WECHAT_OPEN_ID] = openid + "";
  },
  /**
   * 清除openid
   */
  removeOpenIByLocal() {
    localStorage.removeItem(SaveName.WECHAT_OPEN_ID);
  },
  /**
   * 获取openid
   */
  getOpenIdByLocal() {
    return localStorage[SaveName.WECHAT_OPEN_ID];
  },
  /*
  信息展示
  */
  showMsg(_this, msgData, styleParam, isAutoClose) {
    let _jsThis = this;
    _this.$vux.alert.show({ content: _jsThis.alertMsg(msgData, styleParam) });
    if (isAutoClose) {
      setTimeout(() => {
        _this.$vux.alert.hide();
      }, 3000);
    }
    return false;
  },
  alertMsg(data, styleParam) {
    return "<div style='font-size:16px;line-height:24px;color:" + styleParam + "'>" + data + "</div>";
  },
  /**
   * 根据参数名称获取当前URL参数值
   */
  getUrlKey(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null;
  },
  getShareUrlKey(url, name) {
    let urlValue = decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null;
    if (urlValue == null) {
      name = name.toLowerCase();
      urlValue = decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null;
    }
    return urlValue;
  },
  setUuid(_this, uuid) {
    let stateBtn = {
      index: true,
      more: true,
      service: true,
      my: true,
      btn: true,
      isWeChar: false,
      isWeAuth: true,
    }
    if (uuid.indexOf('liberty') > -1 && uuid.length > 10) {
      if (uuid[0] == "0") {
        stateBtn.index = false;
      }
      if (uuid[1] == "0") {
        stateBtn.more = false;
      }
      if (uuid[2] == "0") {
        stateBtn.service = false;
      }
      if (uuid[3] == "0") {
        stateBtn.my = false;
      }
      if (uuid[4] == "0") {
        stateBtn.btn = false;
      }
      if (uuid[5] == "0") {
        stateBtn.isWeChar = true;
      }
      if (uuid[6] == "0") {
        stateBtn.isWeAuth = false;
      }
      _this.$common.storeCommit(_this, Mutations.IS_SHOW_MY, stateBtn);
    }
    // let markNum = uuid.substring(0, 9);
    // if (!isNaN(markNum)) {
    //   if (uuid[10] == "0") {
    //     setTimeout(function () {
    //       _this.$common.storeCommit(_this, Mutations.SET_IS_WE_CHAR_STATE, true);
    //     }, 50);
    //   }
    //   if (uuid[11] == "0") {
    //     _this.$common.storeCommit(_this, Mutations.IS_SHOW_MY, false);
    //   }
    // }
  },
  setUidShareParm(_this) {
    let parm = [];
    let urlParm = {
      key: Url_Key.SHARE_UUID,
      value: _this.saveInsure.refShareUUid
    }
    parm.push(urlParm);
    if (_this.shareData.callBackUrl != "") {
      let callBack = {
        key: Url_Key.REDIRECT_URL,
        value: _this.shareData.callBackUrl
      }
      parm.push(callBack);
    }
    if (_this.shareData.successfulUrl != "") {
      let successfulUrl = {
        key: Url_Key.JUMP_URL,
        value: _this.shareData.successfulUrl
      }
      parm.push(successfulUrl);
    }
    if (_this.shareData.singleMember != "") {
      let singleMember = {
        key: Url_Key.RECORDED_ID,
        value: _this.shareData.singleMember
      }
      parm.push(singleMember);
    }
    if (_this.shareData.successfulUrl != "") {
      let successfulUrl = {
        key: Url_Key.SUCC_URL,
        value: _this.shareData.successfulUrl
      }
      parm.push(successfulUrl);
    }
    if (_this.saveInsure.shareAggerData.agreementCode != "") {
      let agreementCode = {
        key: Url_Key.AGREEMENT_CODE,
        value: _this.saveInsure.shareAggerData.agreementCode
      }
      parm.push(agreementCode);
    }
    if (_this.saveInsure.shareAggerData.salerName != "") {
      let salerName = {
        key: Url_Key.SALER_NAME,
        value: _this.saveInsure.shareAggerData.salerName
      }
      parm.push(salerName);
    }
    if (_this.saveInsure.shareAggerData.salerNumber != "") {
      let salerNumber = {
        key: Url_Key.SALER_NUMBER,
        value: _this.saveInsure.shareAggerData.salerNumber
      }
      parm.push(salerNumber);
    }
    if (_this.saveInsure.shareAggerData.channelName != "") {
      let channelName = {
        key: Url_Key.CHANNEL_NAME,
        value: _this.saveInsure.shareAggerData.channelName
      }
      parm.push(channelName);
    }
    if (_this.saveInsure.shareUid != "") {
      let shareUid = {
        key: Url_Key.UID,
        value: _this.saveInsure.shareUid
      }
      parm.push(shareUid);
    }
    if (_this.shareUid != "") {
      let dealUid = {
        key: Url_Key.DEAL_UUID,
        value: _this.dealUid
      }
      parm.push(dealUid);
    }
    return parm;
  }
}
